package wikist.controller;

import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import wikist.service.PageContentsManagementService;
import wikist.service.StringInWikiNotation;
import wikist.service.PageContentsManagementService.PageContent;

/**
 * Wikiページへのリクエストを受け取るコントローラー
 * 
 * @author onjiro.mohyahya
 */
public class PageRequestController extends Controller {
    private Logger logger =
        Logger.getLogger(PageRequestController.class.getName());

    private PageContentsManagementService contentManagement =
        new PageContentsManagementService();

    @Override
    public Navigation run() throws Exception {
        String pagepath = (String) this.request.getAttribute("page");

        logger.entering(this.getClass().getName(), "run");
        logger.info("following URL is requested. Method="
            + this.request.getMethod()
            + " Page="
            + pagepath);
        try {
            if (this.isGet()) {
                return this.request(pagepath);
            } else if (this.isPost()) {
                return this.entry(pagepath, (String) this.request
                    .getAttribute("title"), new StringInWikiNotation(
                    (String) this.request.getAttribute("content")));
            } else {
                throw new IllegalArgumentException();
            }
        } finally {
            logger.exiting(this.getClass().getName(), "run");
        }
    }

    private Navigation entry(String path, String title,
            StringInWikiNotation content) {
        PageContentsManagementService.PageContent requestPage = null;
        this.contentManagement.entry(path, title, content);
        requestPage = this.contentManagement.get(path);
        this.request.setAttribute("url", path);
        this.request.setAttribute("title", requestPage.getTitle());
        this.request.setAttribute("content", requestPage
            .getContentInHtml()
            .getContent());
        return this.forward("view.jsp");
    }

    private Navigation request(String path) {
        PageContent requestPage = this.contentManagement.get(path);
        logger.info("requested URL="
            + path
            + " "
            + ((requestPage.isNewPage()) ? "not exists." : "already exists."));

        if (requestPage.isNewPage()) {
            this.request.setAttribute("url", path);
            return this.forward("new.jsp");

        } else {
            this.request.setAttribute("url", path);
            this.request.setAttribute("title", requestPage.getTitle());
            this.request.setAttribute("content", requestPage
                .getContentInHtml()
                .getContent());
            return this.forward("view.jsp");
        }
    }

}
